﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;

namespace Tomahawk.Runtime.Rendering.Materials
{
    #region SAS Technique Exceptions
    public class SASUninitializedTechniqueException : Exception
    {
    }
    #endregion

    public sealed class SASTechnique
    {
        private SASScript script;

        private bool valid = false;
        public bool Valid { get { return valid; } }

        private SASMaterial sasEffect;
        public SASMaterial Effect { get { return sasEffect; } }

        private EffectTechnique technique;
        public EffectTechnique Technique { get { return technique; } }

        private Dictionary<string, SASPass> passTable = new Dictionary<string,SASPass>();
        public Dictionary<string, SASPass> PassTable { get { return passTable; } }

        public string Name { 
            get 
            {
                if (technique == null) throw new SASUninitializedTechniqueException();
                return technique.Name; 
            } 
        }

        public bool Initialize(SASMaterial sasEffect, EffectTechnique technique)
        {
            this.sasEffect = sasEffect;
            this.technique = technique;
            this.valid = technique.Validate();

            foreach (EffectAnnotation annotation in technique.Annotations)
            {
                if (annotation.Name.ToUpper() == "SCRIPT")
                {
                    this.script = new SASScript(annotation.GetValueString());
                }
            }

            foreach (EffectPass pass in technique.Passes)
            {
                SASPass sasPass = new SASPass();
                sasPass.Initialize(this, pass);
                passTable.Add(sasPass.Name.ToUpper(), sasPass);
            }

            return true;
        }

        #region Rendering
        public bool DrawMesh(ref SASScript.Context context)
        {
            bool result = true;

            result = script.Execute(ref context);

            return result;
        }
        public bool DrawScene(GraphicsDevice device)
        {
            bool result = true;

            SASScript.Context context = new SASScript.Context(
                Engine.Instance.EffectEnvironment,
                sasEffect,
                this,
                null,
                null,
                null,
                device);

            result = script.Execute(ref context);

            return result;
        }
        #endregion
    }
}
